package com.java.example.util

import android.content.Context
import android.text.TextUtils
import java.io.File
import java.io.FileOutputStream

/**
 */
object AssetsOpenUtil {
    fun copyDir(context: Context, dirName: String) {
        try {
            val list = context.assets.list(dirName)
            if (null != list) {
                for (i in list.indices) {
                    copyFile(context, dirName, list[i])
                }
            }
        } catch (e: Exception) {
        }
    }

    fun copyFile(context: Context, dir: String?, fileName: String) {
        val rootPath = context.getExternalFilesDir(null)!!.absolutePath + if (TextUtils.isEmpty(dir)) "" else File.separator + dir
        val filePath = rootPath + File.separator + fileName
        if (File(filePath).exists()) {
            return
        }
        val rootFile = File(rootPath)
        if (!rootFile.exists()) {
            rootFile.mkdirs()
        }
        try {
            val open = context.assets.open(if (TextUtils.isEmpty(dir)) fileName else dir + File.separator + fileName)
            val fileOutputStream = FileOutputStream(filePath)
            val buffer = ByteArray(1024 * 8)
            var count = 0
            while (open.read(buffer).also { count = it } != -1) {
                fileOutputStream.write(buffer, 0, count)
            }
            open.close()
            fileOutputStream.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}
